import axios from 'axios';
import { ElMessage } from 'element-plus';

let instance = axios.create({
  baseURL: 'http://127.0.0.1:3001',
  timeout: 10000,
  headers: {'X-Custom-Header': 'foobar'}
});

instance.interceptors.request.use(
  config => {
    let token = sessionStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if(response.data.code === 200){
      return response.data;
      }else{
        ElMessage.error(response.data.message);
      }
    }
    return response;
  },
  error => {
    console.log('error',error)
    ElMessage.error('请求失败');
    return Promise.reject(error);
  }
);
export const get = (url: string, data: any) => {
  return new Promise((resolve, reject) => {
    instance.get(url, { params: data }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  })
}
export const post = (url: string, data: any) => {
  return new Promise((resolve, reject) => {
    instance.post(url, data).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  })
}
export default instance;